package com.isaacwaller.digg;

import static com.isaacwaller.digg.DiggInterface.reportError;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ViewStory extends Activity implements OnClickListener {
	public static final String TAG = "DiggViewStory";
	JSONObject digg = null;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewstory);
        
        JSONObject diggs = null;
        try {
			diggs = DiggInterface.makeRequest("story/"+getIntent().getExtras().getInt("id"));
		} catch (ClientProtocolException e) {
			reportError(e);
		} catch (URISyntaxException e) {
			reportError(e);
		} catch (IOException e) {
			reportError(e);
		} catch (JSONException e) {
			reportError(e);
		}
        
		try {
			digg = diggs.getJSONArray("stories").getJSONObject(0);
		} catch (JSONException e1) {
			reportError(e1);
		}
		
        TextView name = (TextView)findViewById(R.id.name);
        TextView desc = (TextView)findViewById(R.id.desc);
        
        
        try {
			name.setText(digg.getString("title"));
			desc.setText(digg.getString("description"));
		} catch (JSONException e) {
			reportError(e);
		}
		
		Button openinbrowser = (Button)findViewById(R.id.openinbrowser);
		openinbrowser.setOnClickListener(this);
    }

	public void onClick(View arg0) {
		Intent i = new Intent();
		i.setAction(Intent.ACTION_VIEW);
		try {
			i.setData(Uri.parse(digg.getString("link")));
		} catch (JSONException e) {
			reportError(e);
		}
		startActivity(i);
	}
}
